var express = require('express');
var router = express.Router();
const { registerLessors, loginLessors, isLessors,getLessors,frozenLessors,getTokenData} = require("../service/lessorsService");
// 引入第二种加密方式
const bcrypt = require('bcrypt');
// 引入生成token工具
const jwt = require('jsonwebtoken');
// 引入常量密钥
const { TOKEN_KEY } = require('../utils/const');


//获取
router.post('/getLessors', async function(req, res, next) {
    const result = await getLessors(req.body)
    console.log(result);
    res.send(result)
})

// 禁用
router.post('/frozenLessors', async function (req, res, next) {
    const data = req.body;
    const result = await frozenLessors(data)
    res.send(result);
});


// 登录
router.post('/loginLessors', async function (req, res, next) {
    const { account, password } = req.body;
    const { data } = await loginLessors({ account })
    if (data == undefined) {
        // 账号验证失败进入if
        res.send({
            message: '登陆失败',
            status: 0
        });
    } else {
        // bcrypt 运用conpareSync进行比较，为true代表密码正确  第二种加密方法
        const isLogin = bcrypt.compareSync(password, data.password);
        if (isLogin) {
            const token = jwt.sign(
                { account },//要保存的用户信息
                TOKEN_KEY,//秘钥字符串
                { expiresIn: "1h" },// 设置 token 的有效期 ，单位 s
            );
            res.send({
                message: '登陆成功',
                status: 1,
                token,
            });//把值响应前端
        } else {
            res.send({
                message: '登陆失败',
                status: 0
            });
        }
    }
});

// 注册
router.post('/registerLessors', async function (req, res, next) {
    const { account, password } = req.body;
    const newpassword = bcrypt.hashSync(password, 10);
    const result = await registerLessors({ account, password: newpassword })
    res.send(result);
});

// 注册判断
router.post('/isLessors', async function (req, res, next) {
    const item = req.body;
    const result = await isLessors(item);
    res.send(result);
})


router.post('/getLessors', async function (req, res, next) {
    res.send(await getLessors());
})

// 获取对应用户的ID
router.post('/getToken', async function (req, res, next) {
    const data = req.body;
    const result = await getTokenData(data)
    res.send(result);
})


module.exports = router;
